import subprocess as sp
from dependence.my_log import MyLoger
import time
mylog = MyLoger().get_logger(__name__)

def cmd_run(*args):
    '''
    执行命令行
    :param args: 执行命令(tuple)
    :return: 返回所有执行结果(str)
    '''
    mylog.debug("执行命令 " + str(*args))
    msg = ''
    res = sp.Popen(*args, shell=True, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE)
    res_stdout = res.stdout.read()
    res_stderr = res.stderr.readlines()
    try:#获取标准输出
        msg = res_stdout.decode("utf-8").replace('\r', '')
        mylog.debug("编码为'utf-8'(stdout): " + str(*args))
    except UnicodeDecodeError:
        try:
            msg = res_stdout.decode("GBK").replace('\r', '')#尝试编码为gbk ping命令会报错
            mylog.error("编码为'GBK'(stdout): " + str(*args))
        except UnicodeDecodeError:
            try:
                msg = res_stdout.decode("ISO-8859-1").replace('\r', '')  # 尝试编码为ISO-8859-1命令会报错#展讯平台adb shell getprop
                mylog.error("编码为'ISO-8859-1'(stdout): " + str(*args))
            except UnicodeDecodeError:
                msg = "执行命令失败,编码错误"
                mylog.error("编码失败: " + str(*args))
    except Exception:
        msg = "执行命令失败"
        mylog.error("执行命令错误: " + str(*args))

    for i in res_stderr:#获取错误输出
        msg += i.decode('gbk').strip()+'\n'
    mylog.debug("执行命令成功(stderr): " + str(*args))
    # mylog.debug("结果为: " + msg)
    '''
    之前使用readlines方式获取输出，readlines或会造成卡死，或只能读取一部分输出，改为使用read读取
    # try:
    #     res = sp.Popen(*args,shell=True,stdin=sp.PIPE,stdout=sp.PIPE,stderr=sp.PIPE)
    #     for i in res.stdout.readlines(100):
    #         print(i)
    #         msg += i.decode('gbk').strip()+'\n'
    #     if msg == '':
    #         for i in res.stderr.readlines():
    #             msg += i.decode('gbk').strip()+'\n'
    #     if msg == '':
    #         msg = '无法获取结果，请检查输入的命令是否正确'
    #     res.wait()
    # except Exception:
    #     mylog.error("执行命令错误: "+ str(*args))
    # mylog.debug("执行命令成功: " + str(*args))
    # mylog.debug("结果为: " + msg)
    '''
    return msg

def cmd_run_show_no_return(control=None,show_msg=None,command=None):
    '''
    cmd命令执行后不需要显示返回信息
    :param control: 展示控件
    :param show_msg: 展示信息
    :param command: 执行cmd命令
    :return:
    '''
    try:
        res_str = cmd_run(command)
        if res_str.startswith("error"):
            control.setText(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + '\n' + res_str)
        else:
            control.setText(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + '\n' + show_msg + " 执行成功,如未显示请重新执行")
        mylog.debug(command + show_msg + "执行成功")
    except Exception:
        control.setText(show_msg + "执行失败")
        mylog.debug(command + show_msg + "执行失败")

def cmd_run_show_with_return(control=None,show_msg=None,command=None):
    '''
    cmd命令执行后需要显示返回信息
    :param control: 展示控件
    :param show_msg: 展示信息
    :param command: 执行cmd命令
    :return:
    '''
    try:
        res_str = cmd_run(command).strip("\r\r\n")
        control.setText(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())+'\n'+res_str)
        mylog.debug(command + show_msg + "执行成功")
    except Exception:
        control.setText(show_msg + "执行失败")
        mylog.debug(command + show_msg + "执行失败")

# if __name__ == '__main__':
#     print(cmd_run("adb devices"))